﻿#include "StartScene.h"
#include "GameScene.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "hero/Hero.h"
#include "layer/HeroUpLayer.h"
#include "layer/WeaponUpLayer.h"
#include "layer/CoinUpLayer.h"
#include "utils/MyStringUtils.h"
#include "utils/AudioUtil.h"
#include "AudioEngine.h"
#include "prop/PropTip.h"
#include "prop/PropTipManager.h"
using namespace experimental;
USING_NS_CC;
using namespace cocos2d;
using namespace cocos2d::ui;
using namespace cocostudio::timeline;
StartScene::StartScene():
	isOpenBtn(false)
{

}

Scene* StartScene::createScene()
{
    auto scene = Scene::create();
    auto layer = StartScene::create();
    scene->addChild(layer);
    return scene;
}

bool StartScene::init()
{
    if ( !Layer::init() )
    {
        return false;
    }
	//重置
	//char filename[20];
	//for (size_t i = 0; i < 3; i++) {
	//	sprintf_s(filename, "num_%d", i + 1);
	//	UserDefault::getInstance()->setIntegerForKey(filename, i + 1);
	//}
	totalCoin = UserDefault::getInstance()->getIntegerForKey("coin", 0);
	//开启背景音乐
	AudioUtil::getInstence()->playBgm();
	initCSBFile();
	initLevelNode();
	openBtnLiener();
	runStartSceneAct();
	initSpriteFrameCache();
	initHero();
	scheduleUpdate();
	schedule(schedule_selector(StartScene::heroMove), 0.1, -1, 0.1);

	//Sprite* test = Sprite::createWithSpriteFrame(gameSpriteCache->getSpriteFrameByName("prop_1.png"));
	//this->addChild(test);
	//test->setPosition(Vec2(size.width / 2, size.height / 2));
    return true;
}

void StartScene::onEnter() {
	Layer::onEnter();
	_eventDispatcher->addCustomEventListener("onShesuUp", [this](EventCustom* event) {
		//金币动画完成后增加金币数
		HeroUpLayer* heroUpLayer = (HeroUpLayer*)event->getUserData();
		subCoin(heroUpLayer->getShesuUpCoinNum());
	});

	_eventDispatcher->addCustomEventListener("onHuoliUp", [this](EventCustom* event) {
		//金币动画完成后增加金币数
		HeroUpLayer* heroUpLayer = (HeroUpLayer*)event->getUserData();
		subCoin(heroUpLayer->getHuoliUpCoinNum());
	});

	_eventDispatcher->addCustomEventListener("onWeaponStrengthUp", [this](EventCustom* event) {
		//金币动画完成后增加金币数
		WeaponUpLayer* weaponUpLayer = (WeaponUpLayer*)event->getUserData();
		subCoin(weaponUpLayer->getStrengthUpCoinNum());
	});

	_eventDispatcher->addCustomEventListener("onWeaponHuoliUp", [this](EventCustom* event) {
		//金币动画完成后增加金币数
		WeaponUpLayer* weaponUpLayer = (WeaponUpLayer*)event->getUserData();
		subCoin(weaponUpLayer->getHuoliUpCoinNum());
	});

	_eventDispatcher->addCustomEventListener("onCoinUp", [this](EventCustom* event) {
		//金币动画完成后增加金币数
		CoinUpLayer* coinUpLayer = (CoinUpLayer*)event->getUserData();
		subCoin(coinUpLayer->getCoinUpCoinNum());
	});

	_eventDispatcher->addCustomEventListener("onProfitUp", [this](EventCustom* event) {
		//金币动画完成后增加金币数
		CoinUpLayer* coinUpLayer = (CoinUpLayer*)event->getUserData();
		subCoin(coinUpLayer->getProfitUpCoinNum());
	});
}

void StartScene::onExit() {
	Layer::onExit();
	UserDefault::getInstance()->setIntegerForKey("coin", totalCoin);
	//移出自定义监听器
	_eventDispatcher->removeCustomEventListeners("onShesuUp");
	_eventDispatcher->removeCustomEventListeners("onHuoliUp");
	_eventDispatcher->removeCustomEventListeners("onWeaponStrengthUp");
	_eventDispatcher->removeCustomEventListeners("onWeaponHuoliUp");
	_eventDispatcher->removeCustomEventListeners("onCoinUp");
	_eventDispatcher->removeCustomEventListeners("onProfitUp");
}

/*
	加载CSB文件
*/
void StartScene::initCSBFile() {
	size = Director::getInstance()->getVisibleSize();
	rootNode = CSLoader::createNode("scenes/start/scene/StartScene.csb");
	this->addChild(rootNode);

	coinNode = dynamic_cast<Node*>(rootNode->getChildByName("coin"));
	levelNode = dynamic_cast<Node*>(rootNode->getChildByName("level"));
	coin_num = dynamic_cast<Text*>(coinNode->getChildByName("coin_num"));
	coin_num->setString(MyStringUtils::getInstance()->coinToString(totalCoin));
	startGame = dynamic_cast<Node*>(rootNode->getChildByName("startGame"));

	layers.push_back(nullptr);
	layers.push_back(nullptr);
	layers.push_back(nullptr);
	char filenames[3][10] = { "heroUp", "weaponUp", "coinUp" };
	for (size_t i = 0; i < 3; i++) {
		Node* upNode = dynamic_cast<Node*>(rootNode->getChildByName(filenames[i]));
		Button* upBtn = dynamic_cast<Button*>(upNode->getChildByName("bgBtn"));
		Sprite* selected = dynamic_cast<Sprite*>(upNode->getChildByName("selected"));
		Sprite* upIcon = dynamic_cast<Sprite*>(upNode->getChildByName("upup"));
		upBtns.push_back(upBtn);
		selecteds.push_back(selected);
		upIcons.push_back(upIcon);

		char filename[80];
		switch (i) {
		case 0:
			sprintf_s(filename, "scenes/start/ui/hero_up_ui.csb");
			break;
		case 1:
			sprintf_s(filename, "scenes/start/ui/weapon_up_ui.csb");
			break;		
		case 2:
			sprintf_s(filename, "scenes/start/ui/coin_up_ui.csb");
			break;
		}
		ActionTimeline* uiAct = CSLoader::createTimeline(filename);
		uiAct->play("upAct", true);
		upNode->runAction(uiAct);
	}

	char filename[80];
	for (size_t i = 0; i < 3; i++) {
		sprintf_s(filename, "start_ui_%d", i + 1);
		Node* starUi = dynamic_cast<Node*>(rootNode->getChildByName(filename));
		startUiNode.push_back(starUi);
	}



}

/*
	初始化关卡结点
*/
void StartScene::initLevelNode() {
	char filename[20];
	for (size_t i = 0; i < 3; i++) {
		sprintf_s(filename, "num_%d", i + 1);
		TextAtlas* num = dynamic_cast<TextAtlas*>(levelNode->getChildByName(filename));
		int level = UserDefault::getInstance()->getIntegerForKey(filename, i + 1);
		num->setString(std::to_string(level));
	}
}

void StartScene::update(float dt) {
	//hero = dynamic_cast<Hero*>(getChildByTag(HERO));
	if (layers[0] != nullptr || layers[1] != nullptr || layers[2] != nullptr) {
		isOpenBtn = true;
	} else {
		isOpenBtn = false;
	}
	//检测是否关闭主机升级层、僚机升级层、金币升级层的升级按钮
	checkCloseBtn();
}

/*
	运行开始场景中的动画
*/
void StartScene::runStartSceneAct() {
	char filename[80];
	ActionTimeline* uiAct = nullptr;
	for (size_t i = 0; i < 3; i++) {
		sprintf_s(filename, "scenes/start/ui/start_ui_%d.csb", i + 1);
		uiAct = CSLoader::createTimeline(filename);
		uiAct->play("run", true);
		startUiNode[i]->runAction(uiAct);
	}

	uiAct = CSLoader::createTimeline("scenes/start/ui/startGame.csb");
	uiAct->play("run", true);
	startGame->runAction(uiAct);
	
}

/*
	判断主机是否移动，移动了则进入游戏场景
*/
void StartScene::heroMove(float dt) {
	hero = Hero::getInstance();
	if (hero->getMoveState()) {
		unschedule(schedule_selector(StartScene::heroMove));
		scheduleOnce(schedule_selector(StartScene::delayEnterGameSence), 0.1);
	}
}

/*
	延迟进入游戏战斗场景
*/
void StartScene::delayEnterGameSence(float dt) {
	MoveTo* mt = MoveTo::create(0.5, Vec2(hero->getPositionX(), 1100));
	CallFunc* call = CallFunc::create([this]() {
		hero->collectionHero();
		//关闭背景音乐
		AudioUtil::getInstence()->stopBgm();
		UserDefault::getInstance()->setIntegerForKey("coin", totalCoin);
		Scene* gameSence = GameScene::createScene();
		auto reSence = TransitionFade::create(3, gameSence);
		Director::getInstance()->replaceScene(reSence);
	});
	Sequence* seqAct = Sequence::create(mt, call, nullptr);
	hero->runAction(seqAct);
}

/*
	加载精灵帧缓存
*/
void StartScene::initSpriteFrameCache() {
	gameSpriteCache = SpriteFrameCache::getInstance();
	gameSpriteCache->addSpriteFramesWithFile("scenes/game/image/sprites.plist",
		Director::getInstance()->getTextureCache()->addImage(
			"scenes/game/image/sprites.png"));		//向帧缓冲中添加纹理图片
}

/*
	初始化英雄
*/
void StartScene::initHero() {
	hero = Hero::getInstance();
	hero->setPosition(Vec2(size.width / 2, size.height / 10 * 2));
	this->addChild(hero);
}

/*
	开启点击事件监听
*/
void StartScene::openBtnLiener() {
	for (int i = 0; i < 3; i++) {
		upBtns[i]->addClickEventListener([this, i](Ref*) {
			AudioUtil::getInstence()->buttonClickSound();
			for (int j = 0; j < 3; j++) {
				if (layers[j] != layers[i] && layers[j] != nullptr) {
					layers[j]->removeFromParent();
					layers[j] = nullptr;
					selecteds[j]->setVisible(false);
				}
			}
			if (layers[i] == nullptr) {
				switch (i) {
					case 0:
						layers[i] = HeroUpLayer::create();
						break;
					case 1:
						layers[i] = WeaponUpLayer::create();
						break;
					case 2:
						layers[i] = CoinUpLayer::create();
						break;
				}
				MoveTo* mt = MoveTo::create(0.3f, Vec2(0, 85));
				layers[i]->runAction(mt);
				heroMoveTo();
				selecteds[i]->setVisible(true);
				this->addChild(layers[i]);
			} else {
				MoveTo* mt = MoveTo::create(0.3f, Vec2(0, -120));
				selecteds[i]->setVisible(false);
				CallFunc* call = CallFunc::create([this, i]() {
					layers[i]->removeFromParent();
					layers[i] = nullptr;
					heroMoveTo();
				});
				Sequence* seqAct = Sequence::create(mt, call, nullptr);
				layers[i]->runAction(seqAct);
			}
		});
	}
}

/*
	检测是否关闭主机升级层、僚机升级层、金币升级层的升级按钮
*/
void StartScene::checkCloseBtn() {
	HeroUpLayer* herolayer = dynamic_cast<HeroUpLayer*>(layers[0]);
	WeaponUpLayer* weaponlayer = dynamic_cast<WeaponUpLayer*>(layers[1]);
	CoinUpLayer* coinlayer = dynamic_cast<CoinUpLayer*>(layers[2]);

	if (herolayer != nullptr) {
		if (totalCoin - herolayer->getShesuUpCoinNum() > 0) {
			herolayer->getShesuBtn()->setEnabled(true);
			herolayer->setShesuUpbtnState(true);
		} else {
			herolayer->getShesuBtn()->setEnabled(false);
			herolayer->setShesuUpbtnState(false);
		}

		if (totalCoin - herolayer->getHuoliUpCoinNum() > 0) {
			herolayer->getHuoliBtn()->setEnabled(true);
			herolayer->setHuoliUpbtnState(true);
		} else {
			herolayer->getHuoliBtn()->setEnabled(false);
			herolayer->setHuoliUpbtnState(false);
		}

		if (herolayer->getShesuUpbtnState() || herolayer->getHuoliUpbtnState()) {
			upIcons[0]->setVisible(true);
		} else {
			upIcons[0]->setVisible(false);
		}
	}
	
	if (weaponlayer != nullptr) {
		if (totalCoin - weaponlayer->getStrengthUpCoinNum() > 0) {
			weaponlayer->getStrengthBtn()->setEnabled(true);
			weaponlayer->setStrengthUpbtnState(true);
		} else {
			weaponlayer->getStrengthBtn()->setEnabled(false);
			weaponlayer->setStrengthUpbtnState(false);
		}

		if (totalCoin - weaponlayer->getHuoliUpCoinNum() > 0) {
			weaponlayer->getHuoliBtn()->setEnabled(true);
			weaponlayer->setHuoliUpbtnState(true);
		} else {
			weaponlayer->getHuoliBtn()->setEnabled(false);
			weaponlayer->setHuoliUpbtnState(false);
		}

		if (weaponlayer->getStrengthUpbtnState() || weaponlayer->getHuoliUpbtnState()) {
			upIcons[1]->setVisible(true);
		} else {
			upIcons[1]->setVisible(false);
		}
	}

	if (coinlayer != nullptr) {
		if (totalCoin - coinlayer->getCoinUpCoinNum() > 0) {
			coinlayer->getCoinBtn()->setEnabled(true);
			coinlayer->setCoinUpbtnState(true);
		} else {
			coinlayer->getCoinBtn()->setEnabled(false);
			coinlayer->setCoinUpbtnState(false);
		}

		if (totalCoin - coinlayer->getProfitUpCoinNum() > 0) {
			coinlayer->getProfitBtn()->setEnabled(true);
			coinlayer->setProfitUpbtnState(true);
		} else {
			coinlayer->getProfitBtn()->setEnabled(false);
			coinlayer->setProfitUpbtnState(false);
		}

		if (coinlayer->getCoinUpbtnState() || coinlayer->getProfitUpbtnState()) {
			upIcons[2]->setVisible(true);
		} else {
			upIcons[2]->setVisible(false);
		}
	}
}

/*
	打开了下方的按钮，主机往前移动一段距离，
	关闭了下方的按钮，主机退回移动的距离
*/
void StartScene::heroMoveTo() {
	
	MoveTo* mt = nullptr;
	if (layers[0] != nullptr || layers[1] != nullptr || layers[2] != nullptr) {
		if (!isOpenBtn) {
			mt = MoveTo::create(0.3, Vec2(hero->getPositionX(), hero->getPositionY() + 200));
			hero->runAction(mt);
		}
	} else {
		mt = MoveTo::create(0.3, Vec2(hero->getPositionX(), hero->getPositionY() - 200));
		hero->runAction(mt);
	}
}

void StartScene::subCoin(int coin) {
		totalCoin -= coin;
		coin_num->setString(MyStringUtils::getInstance()->coinToString(totalCoin));
	//}
}
